package com.mqtt.ctwingmqtt.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mqtt.ctwingmqtt.domain.PageResult;
import com.mqtt.ctwingmqtt.domain.ResponseResult;
import com.mqtt.ctwingmqtt.domain.dto.DeviceDto;
import com.mqtt.ctwingmqtt.domain.entity.DeviceEntity;
import com.mqtt.ctwingmqtt.domain.entity.NIIEntity;
import com.mqtt.ctwingmqtt.domain.vo.DeviceVO;
import com.mqtt.ctwingmqtt.mapper.DeviceMapper;
import com.mqtt.ctwingmqtt.service.DeviceService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, DeviceEntity> implements DeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Override
    public Boolean add(DeviceDto deviceDto) {
        DeviceEntity deviceEntity = new DeviceEntity();
        deviceEntity.setDeviceCode(deviceDto.getDeviceCode());
        String deviceAddress = deviceDto.getDeviceAddress();
        if(deviceMapper.getdeviceAddress(deviceAddress)){
            return false;
        }
        deviceEntity.setDeviceAddress(deviceDto.getDeviceAddress());
        deviceEntity.setDtuId(deviceDto.getDtuId());
        deviceEntity.setDeviceName(deviceDto.getDeviceName());
        deviceEntity.setDeviceType(deviceDto.getDeviceType());
        deviceEntity.setDtuName(deviceDto.getDtuName());
        deviceEntity.setProductId(deviceDto.getProductId());
        //设置创建时间为当前时间
        deviceEntity.setCreatetime(new java.sql.Timestamp(System.currentTimeMillis()));
        deviceEntity.setUpdatetime(new java.sql.Timestamp(System.currentTimeMillis()));
        //设置当前状态为0
        deviceEntity.setStatus("在线");
        int insert = deviceMapper.insertl(deviceEntity);
        return insert > 0;
    }

    @Override
    public Boolean delete(Long id) {
        return deviceMapper.deleteById(id) > 0;
    }

    @Override
    public Boolean update(DeviceDto deviceDto) {
        if (deviceDto == null || deviceDto.getId() == null) {
            return false;
        }
        DeviceEntity deviceEntity = new DeviceEntity();
        BeanUtils.copyProperties(deviceDto, deviceEntity);
        deviceEntity.setUpdatetime(new java.sql.Timestamp(System.currentTimeMillis()));
        return deviceMapper.updateById(deviceEntity) > 0;
    }

    @Override
    public List<DeviceVO> selectAll() {
        List<DeviceEntity> deviceEntities = deviceMapper.selectList(null);
        return deviceEntities.stream()
                .map(this::convertToDeviceVO)
                .collect(Collectors.toList());
    }

    @Override
    public DeviceVO selectOne(Long id) {
        QueryWrapper<DeviceEntity> queryWrapper = Wrappers.query();
        queryWrapper.eq("id", id);
        DeviceEntity deviceEntity = deviceMapper.selectOne(queryWrapper);
        DeviceVO deviceVO = convertToDeviceVO(deviceEntity);
        return deviceVO;
    }


    @Override
    public List<DeviceVO> selectPage(DeviceDto deviceDto) {
            // 1. 构建查询条件
            QueryWrapper<DeviceEntity> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(deviceDto.getDeviceCode())) {
                queryWrapper.like("device_code", deviceDto.getDeviceCode());
            }
            if (StringUtils.isNotBlank(deviceDto.getDeviceName())) {
                queryWrapper.like("device_name", deviceDto.getDeviceName());
            }
            if (StringUtils.isNotBlank(deviceDto.getDeviceAddress())) {
                queryWrapper.eq("device_address", deviceDto.getDeviceAddress());
            }
            if (deviceDto.getDtuId() != null) {
                queryWrapper.eq("dtu_id", deviceDto.getDtuId());
            }
            if (StringUtils.isNotBlank(deviceDto.getDeviceType())) {
                queryWrapper.eq("device_type", deviceDto.getDeviceType());
            }
            if (StringUtils.isNotBlank(deviceDto.getDtuName())) {
                queryWrapper.eq("dtu_name", deviceDto.getDtuName());
            }

            // 2. 执行查询
            List<DeviceEntity> deviceEntities = deviceMapper.selectList(queryWrapper);
            //反转不需要
//            deviceEntities.forEach(deviceEntity -> {
//                String deviceAddress = deviceEntity.getDeviceAddress();
//                deviceEntity.setDeviceAddress(convertDeviceAddress(deviceAddress));
//
//            });

            // 3. 转换为 VO 对象
            return deviceEntities.stream()
                    .map(this::convertToDeviceVO)
                    .collect(Collectors.toList());

    }

    @Override
    public Map<Integer, String> getmp(String deviceAddress) {
        return deviceMapper.getmp(deviceAddress);
    }

    @Override
    public String getProductName(String deviceAddress) {
        return deviceMapper.getProductName(deviceAddress);
    }

    @Override
    public ResponseResult<String> addAll(MultipartFile file) {
        //传入一个excel文件读取文件的前三列作为设备信息 imei 设备id 设备地址（编号）
        //定义返回的结果
        //成功的个数
        int i = 0;
        //失败的设备地址列表
        List<String> errors = new ArrayList<>();
        try {
            //读取文件
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            //遍历行，跳过第一行的表头
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if(row == null)continue;

                // 读取前三列：imei, 设备id, 设备地址（编号）
                String id = getCellValue(row.getCell(0));
                String deviceCode = getCellValue(row.getCell(1));
                String deviceAddress = getCellValue(row.getCell(2));
                if(deviceMapper.getdeviceAddress(deviceAddress)){
                    errors.add(deviceAddress);
                    continue;
                }
                String deviceName =  getCellValue(row.getCell(3));
                String deviceType =  getCellValue(row.getCell(4));
                String dtuId =  getCellValue(row.getCell(5));
                String dtuName =  getCellValue(row.getCell(6));
                String productId =  getCellValue(row.getCell(7));

                DeviceDto deviceDto = new DeviceDto();
                deviceDto.setDeviceAddress(deviceAddress);
                deviceDto.setDeviceCode(deviceCode);
                deviceDto.setDeviceName(deviceName);
                deviceDto.setDeviceType(deviceType);
                deviceDto.setDtuId(Long.parseLong(dtuId));
                deviceDto.setDtuName(dtuName);
                deviceDto.setProductId(productId);
                DeviceEntity deviceEntity = new DeviceEntity();
                BeanUtils.copyProperties(deviceDto,deviceEntity);

                try {
                    int result = deviceMapper.insertl(deviceEntity);
                    if(result > 0){
                        i++;
                    }else errors.add(deviceAddress);
                } catch (Exception e) {
                    errors.add(deviceAddress);
                }

            }
            //关闭工作簿
            workbook.close();

        }catch (Exception e){
            return ResponseResult.error("文件读取失败");
        }
        return ResponseResult.successs(i,errors);
    }

    /**
     * 实体类转为视图层
     * @param deviceEntity
     * @return
     */
    private DeviceVO convertToDeviceVO(DeviceEntity deviceEntity) {
        if (deviceEntity == null) {
            return null;
        }
        DeviceVO deviceVO = new DeviceVO();
        BeanUtils.copyProperties(deviceEntity, deviceVO);
        return deviceVO;
    }

    /**
     * vo转换设备地址
     * @param address
     * @return
     */
    public static String convertDeviceAddress(String address) {
        if (address == null || address.length() % 2 != 0 || address.length() < 12) {
            throw new IllegalArgumentException("Invalid device address format");
        }

        // 将地址按两位分割成组
        List<String> pairs = new ArrayList<>();
        for (int i = 0; i < address.length(); i += 2) {
            pairs.add(address.substring(i, i + 2));
        }

        // 反转组的顺序
        Collections.reverse(pairs);

        // 去掉最后三个组（原前三个00组）
        if (pairs.size() >= 3) {
            pairs.subList(pairs.size() - 3, pairs.size()).clear();
        }

        // 拼接剩余的组
        StringBuilder result = new StringBuilder();
        for (String pair : pairs) {
            result.append(pair);
        }

        return result.toString();
    }



    // 辅助方法：获取单元格的值并转换为字符串
    private String getCellValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                // 使用 DataFormatter 将数值转换为原始字符串
                DataFormatter dataFormatter = new DataFormatter();
                return dataFormatter.formatCellValue(cell);
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return "";
        }
    }
}
